import { http } from "@/utils/http";
import type { Menu } from "./menu";

export type UserResult = {
  success: boolean;
  data: {
    /** token */
    token: string;
    /** 刷新token */
    refreshToken: string;
    /** token过期时间 */
    expires: Date;
    /** 用户信息 */
    userInfo: {
      /** 用户ID */
      id: number;
      /** 头像 */
      avatar: string;
      /** 用户名 */
      username: string;
      /** 昵称 */
      nickname: string;
      /** 当前登录用户的角色 */
      roles: Array<string>;
      /** 按钮级别权限 */
      permissions: Array<string>;
    }
  };
};

export type RefreshTokenResult = {
  success: boolean;
  data: {
    /** `token` */
    accessToken: string;
    /** 用于调用刷新`accessToken`的接口时所需的`token` */
    refreshToken: string;
    /** `accessToken`的过期时间（格式'xxxx/xx/xx xx:xx:xx'） */
    expires: Date;
  };
};

// 登录请求参数
export interface LoginRequest {
  username: string;
  password: string;
}

// 用户登录响应
export interface LoginResponse {
  code: number;
  msg: string;
  data: {
    user: {
      id: number;
      username: string;
      nickname: string;
      avatar: string;
      role_id: number;
      permissions: Array<{
        id: number;
        path: string;
        name: string;
        parentId: number;
        meta: {
          title: string;
          icon: string;
          rank: number;
          auths: string[];
        };
        children?: Array<{
          id: number;
          path: string;
          name: string;
          parentId: number;
          meta: {
            title: string;
            icon: string;
            rank: number;
            auths: string[];
          };
          children?: any[] | null;
        }> | null;
      }>;
    };
    accessToken?: string;
    refreshToken?: string;
    expires?: string;
  };
}

// 用户菜单响应
export interface UserMenuResponse {
  code: number;
  msg: string;
  data: Menu[];
}

// 获取用户信息响应
export interface UserInfoResponse {
  code: number;
  msg: string;
  data: {
    id: number;
    username: string;
    nickname: string;
    avatar: string;
    roles: string[];
  };
}

// 登录
export const login = (data: LoginRequest): Promise<LoginResponse> => {
  return http.request<LoginResponse>("post", "/investor/login", { data });
};

// 获取用户信息
export const getUserInfo = (): Promise<UserInfoResponse> => {
  return http.request<UserInfoResponse>("post", "/investor/user/info");
};

// 获取用户菜单
export const getUserMenus = (): Promise<UserMenuResponse> => {
  return http.request<UserMenuResponse>("post", "/investor/user/menus");
};

/** 登录 */
export const getLogin = (data?: object) => {
  return http.request<any>("post", "/investor/adminlogin", { data });
};

/** 刷新`token` */
export const refreshTokenApi = (data?: object) => {
  return http.request<RefreshTokenResult>("post", "/refresh-token", { data });
};
